﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

namespace DDPAI
{
    internal class HttpHelper
    {
        public static string baseUrl = string.Empty;
        public static string sessionId = string.Empty;

        public static string InitSession()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseUrl + "/vcam/cmd.cgi?cmd=API_RequestSessionID");
            request.Method = "POST";
            request.ContentType = "application/json";

            byte[] payload;
            payload = System.Text.Encoding.UTF8.GetBytes(string.Empty);
            request.ContentLength = payload.Length;

            Stream writer;
            HttpWebResponse response;
            string postContent = string.Empty;

            try
            {
                writer = request.GetRequestStream();
                writer.Write(payload, 0, payload.Length);
                writer.Close();

                response = (HttpWebResponse)request.GetResponse();
                Stream s = response.GetResponseStream();
                StreamReader sRead = new StreamReader(s);
                postContent = sRead.ReadToEnd();
                sRead.Close();
            }
            catch (Exception e)
            {
                writer = null;
                response = null;
                Console.WriteLine("HttpHelper.InitSession > " + e.Message);
            }

            return postContent;
        }

        public static string PostJson(string url, string data) {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseUrl + url);
            request.Method = "POST";
            request.ContentType = "application/json";

            if (!string.IsNullOrEmpty(sessionId))
            {
                request.Headers.Add("Cookie", "SessionID=" + sessionId);
            }

            byte[] payload;
            payload = System.Text.Encoding.UTF8.GetBytes(data);
            request.ContentLength = payload.Length;

            Stream writer;
            HttpWebResponse response;
            string postContent = string.Empty;

            try
            {
                writer = request.GetRequestStream();
                writer.Write(payload, 0, payload.Length);
                writer.Close();

                response = (HttpWebResponse)request.GetResponse();
                Stream s = response.GetResponseStream();
                StreamReader sRead = new StreamReader(s);
                postContent = sRead.ReadToEnd();
                sRead.Close();
            }
            catch (Exception e)
            {
                writer = null;
                response = null;
                Console.WriteLine("HttpHelper.PostJson > " + e.Message);
            }

            return postContent;
        }
    }
}
